#include "fm_udp.h"
#include "ui_fm_udp.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QThread>
#include <iostream>

Fm_UDP::Fm_UDP(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Fm_UDP)
{
    ui->setupUi(this);
    m_qudpSoclet=new QUdpSocket();

}

Fm_UDP::~Fm_UDP()
{
    delete ui;
}

//unicast
void Fm_UDP::on_pushButton_clicked()
{
    //文件选择
    QString filepath = QFileDialog::getOpenFileName(NULL, "请选择数据文件", "", "txt(*.txt)");
    if (filepath.isEmpty())
    {
        QMessageBox::warning(NULL, "提示", "未选择数据文件", "确定");
        return;
    }
    else
    {
        //读取
        QFile f(filepath);
        if(!f.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            std::cout<<"open failed."<<std::endl;
            return ;
        }

        QTextStream txtInput(&f);
        QString lineStr,sendmsg,tmpHand,tmpmsg;
        QString ipadd="127.0.0.1";
        quint16 ipport=8000;
        while(!txtInput.atEnd())
        {
            lineStr = txtInput.readLine();
            //            std::cout << lineStr.toStdString() << std::endl;

            //报文还原
            tmpHand=lineStr.left(3);
            if(tmpHand=="60a")
            {
                QThread::msleep(100);
                sendmsg="can0,"+lineStr.section(' ',0,0).trimmed();
                //                std::cout << sendmsg.toStdString() << std::endl;
                m_qudpSoclet->writeDatagram(sendmsg.toUtf8(),QHostAddress(ipadd),ipport);
            }
            else if(tmpHand=="60b")
            {
                 tmpmsg=lineStr.section(':',0,0).trimmed();

                sendmsg="can0,"+tmpmsg.section('-',0,0).trimmed();
//                std::cout << sendmsg.toStdString() << std::endl;
                m_qudpSoclet->writeDatagram(sendmsg.toUtf8(),QHostAddress(ipadd),ipport);

                sendmsg="can0,"+tmpmsg.section('-',1,1).trimmed();
//                std::cout << sendmsg.toStdString() << std::endl;
                m_qudpSoclet->writeDatagram(sendmsg.toUtf8(),QHostAddress(ipadd),ipport);

                sendmsg="can0,"+tmpmsg.section('-',2,2).trimmed();
//                std::cout << sendmsg.toStdString() << std::endl;
                m_qudpSoclet->writeDatagram(sendmsg.toUtf8(),QHostAddress(ipadd),ipport);
            }

        }



        //发送逻辑
        //    QString ipadd="192.168.183.255";
        //        QString ipadd="127.0.0.1";
        //        quint16 ipport=8000;
        //        m_qudpSoclet->writeDatagram(ui->textEdit->toPlainText().toUtf8(),QHostAddress(ipadd),ipport);
        f.close();
    }
}
